import React, { useState, useEffect, useRef } from 'react';
import _ from 'lodash';
import { connect, useModel, history } from 'umi';
import LoginContainer from './components/loginContainer';
import LoginFormContainer from './components/loginFormContainer';
import { fetchLoginType } from '@/services/user';

export default connect(null, (dispatch) => ({
  userLogin: (payload) => dispatch({ type: 'user/login', payload }),
  checkUserPassword: () => dispatch({ type: 'user/checkPasswordStatus' }),
  openSafeTimeCheck: () => dispatch({ type: 'global/openCheck' }),
  logoutByEmptyResource: () => dispatch({ type: 'user/logout', payload: { withoutLogout: true } }),
}))(({ userLogin, checkUserPassword, openSafeTimeCheck, logoutByEmptyResource }) => {
  const formHandle = useRef(null);
  const { initialState, setInitialState } = useModel('@@initialState');

  const [loginLoading, setLoginLoading] = useState(false);
  const [loginTypes, setLoginTypes] = useState([]);
  const [initialLoading, setInitialLoading] = useState(true);

  // 获取登录方式
  const getLoginTypes = () => {
    return new Promise((resolve) => {
      fetchLoginType()
        .then((res) => {
          resolve(
            _.isArray(res)
              ? _.map(
                  _.filter(res, ({ status, code }) => status === '1' && !!code),
                  ({ code }) => code,
                )
              : [],
          );
        })
        .catch(() => {
          resolve([]);
        });
    });
  };

  // 初始化
  useEffect(() => {
    logoutByEmptyResource();
    if (REACT_APP_EXTRA_LOGIN) {
      return getLoginTypes().then((types) => {
        setLoginTypes(types);
        setInitialLoading(false);
      });
    }
    setInitialLoading(false);
  }, []);

  // 登录操作（表单同步校验通过后）
  const handleLogin = ({ type, params }) => {
    setLoginLoading(true);
    userLogin({ type, params })
      .then(() => {
        const { getUserInfo, getRouterResources } = initialState;
        Promise.all([getUserInfo(), getRouterResources()]).then((result) => {
          const [userInfo, resource] = result;
          setLoginLoading(false);
          const { menuData, defaultUrl } = resource;
          if (menuData && menuData.length) {
            // 若存在访问资源，则登录成功（更新initialState、开启安全操作时间校验、路由跳转）
            setInitialState({
              ...initialState,
              userInfo,
              ...resource,
            });
            history.push(defaultUrl);
            checkUserPassword();
            if (REACT_APP_EFFECTIVE_CHECK) {
              openSafeTimeCheck();
            }
          } else {
            // 清除token、关闭安全操作时间校验、刷新code（2022-9-27刷新code仅账号登录的情况下）
            logoutByEmptyResource();
            const { updateValidCode } = formHandle.current || {};
            if (updateValidCode) {
              updateValidCode();
            }
          }
        });
      })
      .catch((e) => {
        setLoginLoading(false);
        const { code, description } = e || {};
        const { errorHandle } = formHandle.current || {};
        errorHandle && errorHandle({ code, description });
      });
  };

  return (
    <LoginContainer>
      <LoginFormContainer
        ref={formHandle}
        loginTypes={loginTypes}
        loginLoading={loginLoading}
        initialLoading={initialLoading}
        handleLogin={handleLogin}
      />
    </LoginContainer>
  );
});
